package com.cy.cy2025.activity

import android.Manifest
import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.os.Build
import android.os.Bundle
import androidx.annotation.RequiresPermission
import androidx.appcompat.app.AppCompatActivity
import com.amap.api.fence.GeoFence
import com.amap.api.fence.GeoFenceClient
import com.amap.api.fence.GeoFenceClient.GEOFENCE_IN
import com.amap.api.fence.GeoFenceClient.GEOFENCE_OUT
import com.amap.api.fence.GeoFenceClient.GEOFENCE_STAYED
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.DPoint
import com.amap.api.maps.AMap
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.MapsInitializer.updatePrivacyAgree
import com.amap.api.maps.MapsInitializer.updatePrivacyShow
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.MyLocationStyle
import com.cy.cy2025.MyApplication
import com.cy.cy2025.databinding.ActivityAmapTestBinding
import com.cy.cy2025.util.LogUtil
import com.cy.cy2025.util.PermissionUtil
import com.cy.cy2025.util.PermissionsCallback
import com.cy.cy2025.util.ToastUtil


class AMapTestActivity : AppCompatActivity() {

    companion object {
        private const val TAG = "AMapTestActivity"

        fun initAMap() {
            // 初始化高德地图的隐私协议同意和展示设置，建议在应用启动时调用一次即可。不调用地图不能正常使用
            updatePrivacyShow(MyApplication.app, true, true)
            updatePrivacyAgree(MyApplication.app, true)
        }
    }

    val binding by lazy { ActivityAmapTestBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        binding.mapView.onCreate(savedInstanceState)
        binding.mapView.map.apply {
            isTrafficEnabled = true // 显示实时交通状况

            //地图模式可选类型：
            // MAP_TYPE_NORMAL//标准
            // MAP_TYPE_SATELLITE//卫星
            // MAP_TYPE_NIGHT//夜间
            mapType = AMap.MAP_TYPE_NORMAL

            //初始化缩放等级（1-20）
            moveCamera(CameraUpdateFactory.zoomTo(18f))


            // 配置定位样式和行为
            val myLocationStyle = MyLocationStyle()
            // 关键设置：只定位一次，显示位置图标，但不会将地图中心移动到定位点
            // 后续位置更新也不会自动移动地图
            myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE)
            // 设置定位图标是否跟随设备方向旋转
            //myLocationStyle.rotationAngle(0f)
            // 应用定位样式
            setMyLocationStyle(myLocationStyle)

            isMyLocationEnabled = true // 显示当前位置
            //显示定位按钮
            uiSettings.isMyLocationButtonEnabled = true
            //显示缩放按钮
            uiSettings.isGestureScaleByMapCenter = true
            uiSettings.isZoomControlsEnabled = true
            //显示指南针按钮
            uiSettings.isCompassEnabled = true
            //显示比例尺按钮
            uiSettings.isScaleControlsEnabled = true
            //手势操作
            uiSettings.isRotateGesturesEnabled = true
            uiSettings.isScrollGesturesEnabled = true
            //显示倾斜手势操作按钮
            uiSettings.isTiltGesturesEnabled = true
            uiSettings.isZoomGesturesEnabled = true
        }



        PermissionUtil.requestPermissions(object : PermissionsCallback {
            @RequiresPermission(allOf = [Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION])
            override fun onSuccess() {
                initLocation()
                testGeoFence()
            }

            override fun onFailure(
                failures: List<String>,
                forbiddings: List<String>
            ) {
                ToastUtil.showShort("未获得定位权限")
            }
        }, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)


    }


    /**
     * 高德地图带的定位功能
     */
    private fun initLocation() {
        val locationClient = AMapLocationClient(getApplicationContext())
        locationClient.setLocationListener {
            //定位回调逻辑
            if (it != null && it.getErrorCode() == 0) {
                val latLng = LatLng(it.getLatitude(), it.getLongitude())
                //binding.mapView.map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 18f))
                LogUtil.e(TAG, "定位成功,latLng=$latLng")//(22.640186,114.00453)
                // 在这里你可以调用反向地理编码API获取地址信息


            } else {
                //定位失败处理
                LogUtil.e(TAG, "定位失败, ${it.errorCode} : ${it.errorInfo}")
            }
        }
        val option = AMapLocationClientOption()
        option.isOnceLocation = true //单次定位
        locationClient.setLocationOption(option)
        locationClient.startLocation()
    }

    /**
     * 测试地理围栏功能（设置在龙军花园）(22.640186,114.00453)
     */
    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    private fun testGeoFence() {
        //根据得到的定位创建地理围栏
        geoFenceClient = GeoFenceClient(this).apply {
            //设置希望侦测的围栏触发行为，默认只侦测用户进入围栏的行为
            //public static final int GEOFENCE_IN 进入地理围栏
            //public static final int GEOFENCE_OUT 退出地理围栏
            //public static final int GEOFENCE_STAYED 停留在地理围栏内10分钟
            setActivateAction(GEOFENCE_IN or GEOFENCE_OUT or GEOFENCE_STAYED)

            setGeoFenceListener { geoFenceList, errCode, errMsg ->
                if (errCode == GeoFence.ADDGEOFENCE_SUCCESS) {
                    ToastUtil.showShort("地理围栏添加成功")
                    LogUtil.e(TAG, "地理围栏添加成功")
                } else {
                    ToastUtil.showShort("地理围栏添加失败:$errCode--$errMsg")
                    LogUtil.e(TAG, "地理围栏添加失败:$errCode--$errMsg")
                }
            }


            //创建并设置PendingIntent
            createPendingIntent(geofenceBroadcastAction);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                registerReceiver(
                    mGeoFenceReceiver,
                    IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION).apply {
                        addAction(geofenceBroadcastAction)
                    }, RECEIVER_EXPORTED
                )
            } else {
                registerReceiver(
                    mGeoFenceReceiver,
                    IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION).apply {
                        addAction(geofenceBroadcastAction)
                    })
            }



            //添加地理围栏 （根据提供的坐标和范围，sdk自动去搜索指定的名称和类型，搜不到就会失败）
            addGeoFence(
                "老妈土钵菜",
                "餐厅",
                DPoint(22.640186, 114.00453),
                500f, // 半径，单位米
                2,
                "471235(as是的撒的)"
            )

        }
    }

    var geoFenceClient: GeoFenceClient? = null

    //定义接收广播的action字符串
    val geofenceBroadcastAction = "com.location.apis.geofencedemo.broadcast";

    val mGeoFenceReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent) {
            if (intent.action == geofenceBroadcastAction) {
                //解析广播内容

                intent.extras?.let {
                    //获取围栏行为：
                    val status = it.getInt(GeoFence.BUNDLE_KEY_FENCESTATUS)

                    //获取自定义的围栏标识：
                    val customId = it.getString(GeoFence.BUNDLE_KEY_CUSTOMID)

                    //获取围栏ID:
                    val fenceId = it.getString(GeoFence.BUNDLE_KEY_FENCEID)

                    //获取当前有触发的围栏对象：
                    val fence = it.getParcelable<GeoFence?>(GeoFence.BUNDLE_KEY_FENCE)

                    LogUtil.e(
                        TAG,
                        "地理围栏广播 : status=$status,customId=$customId,fenceId=$fenceId,fence=$fence"
                    )
                }


            }
        }
    }

    override fun onResume() {
        super.onResume()
        binding.mapView.onResume()
    }

    override fun onPause() {
        super.onPause()
        binding.mapView.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        binding.mapView.onDestroy()
        //会清除所有围栏
        geoFenceClient?.removeGeoFence();
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        binding.mapView.onSaveInstanceState(outState)
    }
}